/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

enum Continuity {
  Position = 0,
  Tangent = 1,
  Curvature = 3,
}

type FormData = {
  curve1?: pickedLineData;
  point1?: pickedVertexData;
  continuity1: Continuity;
  degree1: number;
  curve2?: pickedLineData;
  point2?: pickedVertexData;
  continuity2: Continuity;
  degree2: number;
};

type ParamsCurve = {
  id: string;
  point: string;
  continuity: Continuity;
  degree: number;
};

type Params = {
  curve1: ParamsCurve;
  curve2: ParamsCurve;
};

function CommandBlendCurve({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    continuity1: Continuity.Position,
    degree1: 1,
    continuity2: Continuity.Position,
    degree2: 1,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  const execute = async (preview: boolean) => {
    const {
      curve1,
      point1,
      continuity1,
      degree1,
      curve2,
      point2,
      continuity2,
      degree2,
    } = formData;

    const params: Params = {
      curve1: {
        id: curve1.edgeId,
        point: point1.vertexId,
        continuity: continuity1,
        degree: degree1,
      },
      curve2: {
        id: curve2.edgeId,
        point: point2.vertexId,
        continuity: continuity2,
        degree: degree2,
      },
    };

    await confirmCommand({ type: 'Blend', a: params }, preview);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { curve1, curve2 } = params;

    await initEditDependency([
      curve1.id,
      curve1.point,
      curve2.id,
      curve2.point,
    ]);

    setFormData({
      curve1: picker.generatePickObjByPickID(curve1.id) as pickedLineData,
      point1: picker.generatePickObjByPickID(curve1.point) as pickedVertexData,
      continuity1: curve1.continuity,
      degree1: curve1.degree,
      curve2: picker.generatePickObjByPickID(curve2.id) as pickedLineData,
      point2: picker.generatePickObjByPickID(curve2.point) as pickedVertexData,
      continuity2: curve2.continuity,
      degree2: curve2.degree,
    });
  }, []);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-blend-curve', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const isFormDataValid = () => {
    const { curve1, point1, degree1, curve2, point2, degree2 } = formData;

    return (
      curve1 != null &&
      point1 != null &&
      degree1 != null &&
      curve2 != null &&
      point2 != null &&
      degree2 != null
    );
  };

  const preview = async () => {
    clear();
    if (!isFormDataValid()) {
      return;
    }

    await execute(true);
  };

  const continuitySchema = {
    type: 'number',
    oneOf: [
      {
        type: 'number',
        title: '位置',
        const: 0,
      },
      {
        type: 'number',
        title: '切线',
        const: 1,
      },
      {
        type: 'number',
        title: '曲率',
        const: 3,
      },
    ],
    default: 0,
  } as RJSFSchema;

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve1: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      point1: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      continuity1: {
        title: '曲线1连续方式',
        ...continuitySchema,
      },
      degree1: {
        type: 'number',
        title: '曲线1参数',
        format: NumberInputFormat.Real,
      },
      curve2: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      point2: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      continuity2: {
        title: '曲线2连续方式',
        ...continuitySchema,
      },
      degree2: {
        type: 'number',
        title: '曲线2参数',
        format: NumberInputFormat.Real,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      submitLoading={isLoading}
      extraUiSchema={{
        curve1: {
          'ui:placeholder': '请输入曲线1',
          'ui:autofocus': true,
        },
        point1: {
          'ui:placeholder': '请输入曲线1上的点',
        },
        curve2: {
          'ui:placeholder': '请输入曲线2',
        },
        point2: {
          'ui:placeholder': '请输入曲线2上的点',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdBlendCurve: CurvedBaseCommand = {
  id: 'CmdBlendCurve',
  label: 'command.blend-curve',
  icon: 'commands/curved/blend-curve',
  create: (label, onClose, props) => (
    <CommandBlendCurve
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
